/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "Launcher.h"

#include "Console.h"

/////////////////////////////////////////////////////////////////////////////
//
// Launcher Namespace
//

bool Launcher::Launch( __in const std::string GameLauncherPath,
					   __in const DWORD PriorityClass,
					   __in const DWORD AffinityMask,
					   __in const bool AutoClickGameLauncherPlayButton )
{
	Console::PrintProgressInfo( "attempting to launch 'GameLauncher'" );

	STARTUPINFO				StartUpInfo;
	PROCESS_INFORMATION		ProcessInformation;

	ZeroMemory( &StartUpInfo, sizeof( StartUpInfo ) );
	StartUpInfo.cb = sizeof( StartUpInfo );
	ZeroMemory( &ProcessInformation, sizeof( ProcessInformation ) );

	if( CreateProcess( GameLauncherPath.c_str( ),
					   NULL,
					   NULL,
					   NULL,
					   FALSE,
					   PriorityClass,
					   NULL,
					   NULL,
					   &StartUpInfo,
					   &ProcessInformation )
	  )
	{
		Console::PrintProgressResult( CONSOLE_PROGRESS_RESULT_SUCCEEDED );

		Console::PrintProgressInfo( "checking priority class" );

		if( GetPriorityClass( ProcessInformation.hProcess ) == PriorityClass )
			Console::PrintProgressResult( CONSOLE_PROGRESS_RESULT_SUCCEEDED );
		else
			Console::PrintProgressResult( CONSOLE_PROGRESS_RESULT_FAILED );

		Console::PrintProgressInfo( "changing affinity mask" );

		if( ChangeProcessAffinityMask( ProcessInformation.hProcess, AffinityMask ) )
			Console::PrintProgressResult( CONSOLE_PROGRESS_RESULT_SUCCEEDED );
		else
			Console::PrintProgressResult( CONSOLE_PROGRESS_RESULT_FAILED );

		WaitForSingleObject( ProcessInformation.hProcess, INFINITE );

		CloseHandle( ProcessInformation.hProcess );
		CloseHandle( ProcessInformation.hThread );

		AutoClickPlayButton( AutoClickGameLauncherPlayButton );

		return true;
	}
	Console::PrintProgressResult( CONSOLE_PROGRESS_RESULT_FAILED );
	return false;
}

bool Launcher::ChangeProcessAffinityMask( __in HANDLE ProcessHandle, __in const DWORD AffinityMask )
{
	if( SetProcessAffinityMask( ProcessHandle,  AffinityMask ) )
		return true;
	else
		return false;
}

void Launcher::AutoClickPlayButton( bool Enable )
{
	if( Enable )
	{
		Console::PrintProgressInfo( "auto-clicking play button" );
		HWND GameLauncherWindowHandle = FindWindow( "StartUpDlgClass", "MapleStory" );

		if( GameLauncherWindowHandle != NULL )
		{
			SendMessage( FindWindowEx( GameLauncherWindowHandle,
						 NULL, "Button", "Play!" ),
						 WM_LBUTTONDOWN,
						 1, 1 );
			SendMessage( FindWindowEx( GameLauncherWindowHandle,
						 NULL, "Button", "Play!" ),
						 WM_LBUTTONUP,
						 1, 1 );
			Console::PrintProgressResult( CONSOLE_PROGRESS_RESULT_UNKNOWN );
		}
		else
			Console::PrintProgressResult( CONSOLE_PROGRESS_RESULT_FAILED );
	}
}